package com.es.queue;


/**
 * @author 二十
 * @since 2022/1/17 1:56 上午
 */
public class TailLinkedListQueue<E> extends AbstractQueue<E> {


    @Override
    public void enqueue(E e) {
        if (tail == null) {
            tail = new Node<>(e);
            head = tail;
            size++;
            return;
        }
        Node<E> t = new Node<>(e);
        tail.next = t;
        tail = t;
        size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("error");
        }

        Node<E> t = head;

        head = head.next;

        if (head == null) {
            tail = null;
        }
        return t.e;
    }

    @Override
    public E getFront() {
        return head.e;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }


    private Node<E> head, tail;

    private int size;

    private class Node<E> {
        E e;
        Node<E> next;

        public Node(E e, Node node) {
            this.next = node;
            this.e = e;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return "Node{" +
                    "e=" + e +
                    '}';
        }
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder("Queue:[");
        Node<E> p;
        for (p = head; p != tail; p = p.next) {
            sb.append(p.e).append("<-");

        }
        sb.append(p.e);
        return sb.append("]").toString();
    }
}
